When assigning 2 variables with decimal point numbers and calculating the sum of both of them when using console.log() to return the result if they equal the whole number they return it without the decimal point.
For example
let num1 = 2.2;
let num2 = 2.8;
console.log(num1 + num2 )
returns 5 when I require 5.0 to be returned.
I've tried toFixed(1) but the test requires various numbers to be returned
For example
let num1 = 2.22
let num2 = 2.71
console.log((num1 + num2)toFixed(1))
returns 4.9 when I require 4.93
Is there a way I can assign the variable a floating-point decimal and keep its status even in the return value is a whole number?
The thing is you don't know how many decimal place there is before the addition.
So assuming you would like to keep the longuest amount of decimal places, you could write a function like this:
function decimalPlaces(arr) {
return Math.max(...arr.map(n => n.toString().split(".")[1].length))
}
console.log((2.8 + 2.2).toFixed(decimalPlaces([2.8, 2.2])))
console.log((2.22 + 2.71).toFixed(decimalPlaces([2.22, 2.71])))
console.log((1.7 + 1.3001).toFixed(decimalPlaces([1.7, 1.3001])))
But notice that you have to pass the original numbers to the function in an array... Up to you to decide if it's useful.
function add(num1, num2) {
const num1PointLength = String(num1).split(".")[1]?.length || 0;
const num2PointLength = String(num2).split(".")[1]?.length || 0;
return (num1 + num2).toFixed(num1PointLength > num2PointLength ? num1PointLength : num2PointLength);
}
let num1 = 2.2;
let num2 = 2.8;
console.log(add(num1, num2));
toFixed()-> this method rounds the string to a specified number of decimals.If the number of decimals are higher than in the number, zeros are added.
let num1 = 2.2
let num2 = 2.8
console.log((num1 + num2).toFixed(1))
returns=> 5.0